import { NavBar, Button, Input } from 'antd-mobile'
import React, { useEffect, useMemo, useState } from 'react'
import styles from './msg.module.css'
import uselodash from '../../hooks/uselodash'

function Index() {
  let [data, setdata] = useState([])
  let user_id = 1
  let server_id = 5432
  const [value, setValue] = useState('')
  const socket = useMemo(() => {
    // Create WebSocket connection.
    return new WebSocket(`ws:113.44.139.133:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`);
  }, [])

  useEffect(() => {
    // Connection opened
    socket.addEventListener("open", function (event) {
      socket.send(JSON.stringify({ type: 'getChatList' }));
    });

    // Listen for messages
    socket.addEventListener("message", function (event) {
      console.log("Message from server ", JSON.parse(event.data));
      let msg = JSON.parse(event.data)
      if (msg.type == 'getChatList') {
        setdata(msg.data)
      } else if (msg.type == 'addMessage') {
        setdata([...msg.data, ...value])
      }
    });
  }, [])

  let fa = uselodash(() => {
    socket.send(JSON.stringify({
      type: 'addMessage',
      data: {
        user_id,
        server_id,
        message: value
      }
    }));
    setValue('')
  }, 1000)

  return (
    <div>
      <NavBar>聊天</NavBar>
      <div style={{ height: '90vh' }}>
        <main style={{ height: '85vh', overflow: 'hidden' }}>
          <div style={{ height: '85vh', overflow: 'auto' }}>
            {/* 列表 */}

            {
              data.length > 0 && data.map((item, index) => {
                return <div className={item.dir == 1 ? styles.list1 : styles.list} key={index}>
                  <img style={{ width: '40px', height: '40px', borderRadius: '50%' }} src={item.dir == 1 ? item.user_avatar : item.server_avatar} alt="" />
                  <div>
                    <p style={{ padding: '3px 5px', background: 'yellow', margin: '0 5px' }}>{item.message}</p>
                  </div>
                </div>
              })
            }
          </div>
        </main>
        <footer style={{ display: 'flex', justifyContent: 'space-around', height: '5vh' }}>
          <Input type="text" style={{ width: '80%' }} value={value}
            onChange={val => {
              setValue(val)
            }} /><Button onClick={() => fa()}>发送</Button>
        </footer>
      </div>
    </div>
  )
}

export default Index
